<?php
	/**
	* Department module
	* @author trungdt
	* @since Sep 1, 2011
	* 
	* Change logs
	* 
	*/

	class depmodule {
		function name() { return "Department Module"; }
		function description() { return "Manage Department"; }
		function author() { return "ABSoft.vn"; }

		function hasSources() { return true; }
		function hasContent() { return true; }
		function hasViews() { return true; }

		function supportsWorkflow() { return false; }

		function permissions($internal = "") {
			return array(
			'administrate'=>'Administrate',
			'configure'=>'Configure',
			'create'=>'Create Links',
			'edit'=>'Edit Links',
			'delete'=>'Delete Links'
			);
		}

		function show($view,$loc = null, $title = "") {
			global $db;

			$config = $db->selectObject('depmodule_config',"location_data='".serialize($loc)."'");
			if ($config == null) {
				// not configured? Must be configure first
				$params=array();
				$params['module']=$loc->mod;
				$params['action']='configure';
				$params['src']=$loc->src;
				$params['_common']=1;
				$link=exponent_core_makeLink($params);
				echo "This module is not configured. <a href='{$link}'>Click here to configure this module</a>";
			}
			else
			{
				/// build dep link, the link back to the section 
				$location_data=serialize($loc);
				$mysec=depmodule::getSectionContainDep($location_data);
				$dep_link="";
				if ($mysec)
				{
					$params=array();
					$params['section']=$mysec->section;
					$dep_link=exponent_core_makeLink($params);
				}

				$links=depmodule::getTreeLinks($location_data);

				$template = new template('depmodule',$view,$loc);
				$template->assign('config',$config);
				$template->assign('dep_link',$dep_link);
				$template->assign('links',$links);
				// fake current_node
				$current_node=null; $current_node->dont_show_info=0;
				$current_node->article_src=$mysec->sef_name.$mysec->id;
				$current_node->module_name=$config->module_name;
				$template->assign('current_node',$current_node);
				$template->assign('breadcum_count',0);

				$template->assign('main_content',$config->source_main);
				$template->register_permissions(array('administrate','configure','create','edit','delete'),$loc);
				$template->output();
			}
		}

		/**
		* This function return modules that can be included able by department module
		* 
		*/
		static function __Module_Includeable(){
			$module_type=array();
			$module_type[""]="Dont show";
			$module_type["articlemodule"]="Article/Listing";
			$module_type["calendarmodule"]="Calendar";
			$module_type["contactmodule"]="Contact";
			$module_type["containermodule"]="Container";
			$module_type["newsmodule"]="News";
			return $module_type;
		}
		
		/**
		* Get all link in tree
		* @author trungdt
		* @since Sep 1, 2011
		* @param mixed $loc
		* @param mixed $selected_node seo name of selected node
		* @return array Nodes array
		*/
		static function getTreeLinks($loc, $selected_node="")
		{
			global $db;
			$items=$db->selectObjects("depmodule_dep","location_data = '{$loc}'","  parent_id, rank");

			// after that, we search for the selected node. Hey boy, where are you?
			$temp_search=array();
			$temp_obj=null;
			foreach ($items as $k=>$v){
				if ($v->seo_name == $selected_node)
				{
					$temp_obj=$v;
					$temp_search[]=$k;
					break;
				} 
			}
			//
			if ($temp_obj)
			{
				do{
					$flag=true;
					foreach ($items as $k=>$v){
						if ($v->id == $temp_obj->parent_id){
							$temp_search[]=$k;
							$temp_obj=$v;
							$flag=false;
							break;
						}
					}
					if ($flag) break;
				} while ($temp_obj->parent_id != 0);
			}
			//
			$result=array();
			depmodule::putNodeonTree($items, $result, $temp_search, count($temp_search)-1);
			//
			return $result;
		}

		static function putNodeonTree(&$items, &$result, $temp_search,  $index){
			// stop the loop
			if (($index < 0) && count($temp_search)>0)
				return;
			// because the $items has been sorted before, we search linear
			if (count($temp_search) > 0)
				$parent_id = $items[$temp_search[$index]]->parent_id;
			else
				$parent_id = 0;
			foreach ($items as $k=>$v){
				if ($v->parent_id == $parent_id ){
					$v->depth = count($temp_search)-$index;
					if ((count($temp_search) > 0) && ($k == $temp_search[$index]))
					{
						$v->expanded=1;
						if ($index == 0)
							$v->active=1;
						else
							$v->active=0;
					}
					$result[]=clone $v;   
					if (count($temp_search) >0 && ($k == $temp_search[$index])) // this is the selected node
					{
						if ($index == 0) // last node
						{
							// put all sub nodes of last node into here
							foreach ($items as $k1=>$v1)
							{
								if ($v1->parent_id == $v->id) // sub nodes
								{
									$v1->depth=$v->depth+1;
									$result[]=clone $v1;
								}
							}
						}
						depmodule::putNodeonTree($items, $result, $temp_search,$index-1 ); 
					}
				}
			}
		}

		/**
		* Get the section that is the container of this Department
		* @return object null if can not find, section object if found
		* @param mixed $loc location of department module
		*/
		static function getSectionContainDep($loc)
		{
			global $db;

			$temp=$db->selectObject("container","internal = '{$loc}'");
			if ($temp)
			{
				$temp=unserialize($temp->internal)->src;
				$sql="SELECT * FROM {$db->prefix}section 
				INNER JOIN {$db->prefix}sectionref
				ON {$db->prefix}section.id = {$db->prefix}sectionref.section
				WHERE {$db->prefix}sectionref.source = '{$temp}'";
				$temp=$db->selectObjectsBySql($sql);
				if (count($temp) > 0)
					$temp=array_pop($temp);
				return $temp;
			}
			else
				return null;   
		}

		function deleteIn($loc) {
			global $db;
			$db->delete('depmodule_dep',"location_data='".serialize($loc)."'");
			$db->delete('depmodule_config',"location_data='".serialize($loc)."'");
		}

		function copyContent($oloc,$nloc) {
			foreach ($db->selectObjects('depmodule_dep',"location_data='".serialize($oloc)."'") as $l) {
				$l->location_data = serialize($nloc);
				$db->insertObject($l,'depmodule_dep');
			}
		}

		function searchName() {
			return "Department";
		}

		/*
		8/29/2009 immanuel192
		This function create HTML content of spider item
		*/
		function spiderTemplate($album)
		{
			global $db;


			// create template content
			$template=new template("linklistmodule","_search");
			$template->assign("album",$album);
			ob_start();
			$template->output();
			$get_value=ob_get_contents();
			ob_end_clean(); 
			return $get_value;
		}


		/*
		Feb 24, 2011 - trungdt - Temporary disable linklist search support
		function spiderContent($item = null) {
		global $db;

		if (!defined('SYS_SEARCH')) require_once(BASE.'subsystems/search.php');

		$search = null;
		$search->category = 'Links';
		$search->ref_module = 'linklistmodule';
		$search->ref_type = 'linklist_link';
		$search->view_link = '';

		if ($item) {
		$db->delete('search',"ref_module='linklistmodule' AND ref_type='linklist_link' AND original_id=" . $item->id);
		$search->original_id = $item->id;
		$search->title = ' ' . $item->name . ' ';
		$search->body = ' ' . exponent_search_removeHTML($item->description) . ' ';
		$search->location_data = $item->location_data;
		$db->insertObject($search,'search');
		} else {
		$db->delete('search',"ref_module='linklistmodule' AND ref_type='linklist_link'");
		foreach ($db->selectObjects('linklist_link') as $item) {
		$search->original_id = $item->id;
		$search->title = ' ' . $item->name . ' ';
		$search->body = ' ' . exponent_search_removeHTML($item->description) . ' ';
		$search->location_data = $item->location_data;
		$db->insertObject($search,'search');
		}
		}

		return true;
		}
		*/


		/**
		* @author trundt
		* @since Sep 16, 2011 - trungdt
		* 
		* Generate Department at level 1 to selected section. all must be configured first
		* Sep 16, 2011 - trungdt - 
		* 
		*/
		static function  _SectionGenerate($sections)
		{
			global $db;

			$deps=$db->selectAndJoinObjects(null,'section_seo_name',"depmodule_dep","depmodule_config","location_data","location_data","dep_to_section = 1 AND parent_id =0", "location_data, rank");

			/*$sql="SELECT {$db->prefix}depmodule_dep.* 
			FROM  {$db->prefix}depmodule_dep INNER JOIN {$db->prefix}depmodule_config 
			ON {$db->prefix}depmodule_dep.location_data = {$db->prefix}depmodule_config.location_data
			WHERE dep_to_section = 1";;
			*/

			// loop all the deps we have
			do
			{
				// shift the first element
				$cur_dep = array_shift($deps);

				// search for the right section object
				$obj=null;
				$section_menu_id="";
				$save_last_array_part=array();
				foreach ($sections as $k=>$v)
				{
					if (isset($cur_dep->section_seo_name) && ($v->sef_name == $cur_dep->section_seo_name))
					{
						$flag_reset_foreach=false;

						$obj = clone $v;
						// we increase the depth, for automatic menu generate
						$obj->depth++;
						$section_menu_id=$v->id;
						$temp=array_chunk($sections,$k+1); // we split into 2 part hehe
						// Sep 18, 2011 - trungdt - Fix recursive all 
						$sections=$temp[0];
						
						for ($i=1;$i<count($temp);$i++){
							$save_last_array_part=array_merge($save_last_array_part, $temp[$i]);
						}
						
						

						// now, we generate the department into here
						// first , we unshift the $deps
						array_unshift($deps, $cur_dep);
						// loop and generate

						while ($cur_dep->section_seo_name == $v->sef_name)
						{
							$cur_dep=array_shift($deps);
							// return if not the same
							if ($cur_dep == null)
								break;
							if ($cur_dep->section_seo_name == $v->sef_name)
							{
								$obj->id=$cur_dep->id*rand(1,10);
								$obj->name=$cur_dep->title;
								$obj->sef_name=$cur_dep->seo_name;
								$params['module']="depmodule";
								$params['action']="view";
								$params['id']=$cur_dep->seo_name;
								$temp=unserialize($cur_dep->location_data);
								$params['src']=$temp->src;
								$obj->link=exponent_core_makeLink($params);
								$obj->parents=array($section_menu_id);
								$sections[]=clone $obj;
							}
							else
							{
								array_unshift($deps, $cur_dep);
								$flag_reset_foreach=true;
								break;
							}
						}

						$sections=array_merge($sections, $save_last_array_part);

						if ($flag_reset_foreach)
							break;
					}
				}

			} while (count($deps) > 0);

			return $sections;
		}
	}
?>
